package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private IStrategyCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void saveOrUpdate(StrategyComment strategyComment) {
        if(!StringUtils.hasLength(strategyComment.getId())){
            strategyComment.setCreateTime(new Date());
        }

        repository.save(strategyComment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        //查询条件
        Query query = new Query();

        //判断
        if(qo.getDetailId() != -1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        //count 查询总数
        long count = template.count(query, StrategyComment.class);

        //判断是否有符合条件的评论
        if(count == 0){
            return Page.empty();
        }
        //分页条件
        Pageable pageable = PageRequest.of(qo.getCurrentPage() -1 ,qo.getPageSize(),new Sort(Sort.Direction.DESC,"createTime"));
        query.with(pageable);


        List<StrategyComment> strategyComments = template.find(query, StrategyComment.class);

        return new PageImpl(strategyComments,pageable,count);
    }

    @Override
    public void commentThumbUp(String commentId, Long userId) {

        StrategyComment comment = repository.findById(commentId).get();

        //1.判断用户是否在list中
        List<Long> thumbuplist = comment.getThumbuplist();
        if(thumbuplist.contains(userId)){
            //点赞数-1
            comment.setThumbupnum(comment.getThumbupnum()-1);
            //删除用户id(取消点赞)
            thumbuplist.remove(userId);
        }else{
            //表示不存在
            //点赞数+1
            comment.setThumbupnum(comment.getThumbupnum() + 1 );
            //将用户加进list里
            thumbuplist.add(userId);
        }

        this.saveOrUpdate(comment);
    }
}
